package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class RandomHandler extends EventDispatcher
	{
		private static var instance:RandomHandler;
		private var _lastResult:ArrayCollection;
		
		[Bindable ("randomResult")]
		public function get lastResult():ArrayCollection{
			return _lastResult;
		}
		
		public function RandomHandler(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public function requestRandomImages():void{
			dispatchEvent(new Event("requestingRandom"));
			var servletRequest:HTTPService = new HTTPService();
			servletRequest.method = "GET";
			servletRequest.url = Settings.getInstance().randomServletURL;
			servletRequest.addEventListener(ResultEvent.RESULT,resultHandler);
			servletRequest.send();
		}
		
		private function resultHandler(event:ResultEvent):void{
			_lastResult = Parser.parseServletResult(event);
			if(_lastResult == null){
				dispatchEvent(new Event("randomError"));
			}else{
				dispatchEvent(new ResultEvent("randomResult",false,true,lastResult));
			}
		}
		
		public static function getInstance():RandomHandler{
			if(instance == null)
				instance = new RandomHandler();
			return instance;
		}
	}
}